<!DOCTYPE html>
<html lang="en-US">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width,initial-scale=1">
    <title>利用Excutors异步执行任务 | ggBall&#39;s blog</title>
    <meta name="generator" content="VuePress 1.7.1">
    <link rel="icon" href="/docslogo.jpg">
    <meta name="description" content="我的个人网站">
    
    <link rel="preload" href="/docs/assets/css/0.styles.98990512.css" as="style"><link rel="preload" href="/docs/assets/js/app.491c5ace.js" as="script"><link rel="preload" href="/docs/assets/js/2.dc29a537.js" as="script"><link rel="preload" href="/docs/assets/js/13.c24cbb66.js" as="script"><link rel="prefetch" href="/docs/assets/js/10.f214bc15.js"><link rel="prefetch" href="/docs/assets/js/11.cdbf7171.js"><link rel="prefetch" href="/docs/assets/js/12.f4762cca.js"><link rel="prefetch" href="/docs/assets/js/3.3ee4d975.js"><link rel="prefetch" href="/docs/assets/js/4.6a696fcd.js"><link rel="prefetch" href="/docs/assets/js/5.8bd4db56.js"><link rel="prefetch" href="/docs/assets/js/6.49cb30a3.js"><link rel="prefetch" href="/docs/assets/js/7.17dfae7a.js"><link rel="prefetch" href="/docs/assets/js/8.f4feab71.js"><link rel="prefetch" href="/docs/assets/js/9.af7d9bf1.js">
    <link rel="stylesheet" href="/docs/assets/css/0.styles.98990512.css">
  </head>
  <body>
    <div id="app" data-server-rendered="true"><div class="theme-container"><header class="navbar"><div class="sidebar-button"><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" role="img" viewBox="0 0 448 512" class="icon"><path fill="currentColor" d="M436 124H12c-6.627 0-12-5.373-12-12V80c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12zm0 160H12c-6.627 0-12-5.373-12-12v-32c0-6.627 5.373-12 12-12h424c6.627 0 12 5.373 12 12v32c0 6.627-5.373 12-12 12z"></path></svg></div> <a href="/docs/" class="home-link router-link-active"><!----> <span class="site-name">ggBall's blog</span></a> <div class="links"><div class="search-box"><input aria-label="Search" autocomplete="off" spellcheck="false" value=""> <!----></div> <nav class="nav-links can-hide"><div class="nav-item"><a href="/docs/accumulate/" class="nav-link">
  前端基础
</a></div><div class="nav-item"><a href="/docs/algorithm/" class="nav-link">
  算法题库
</a></div><div class="nav-item"><a href="https://baidu.com" target="_blank" rel="noopener noreferrer" class="nav-link external">
  微博
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav></div></header> <div class="sidebar-mask"></div> <aside class="sidebar"><nav class="nav-links"><div class="nav-item"><a href="/docs/accumulate/" class="nav-link">
  前端基础
</a></div><div class="nav-item"><a href="/docs/algorithm/" class="nav-link">
  算法题库
</a></div><div class="nav-item"><a href="https://baidu.com" target="_blank" rel="noopener noreferrer" class="nav-link external">
  微博
  <span><svg xmlns="http://www.w3.org/2000/svg" aria-hidden="true" focusable="false" x="0px" y="0px" viewBox="0 0 100 100" width="15" height="15" class="icon outbound"><path fill="currentColor" d="M18.8,85.1h56l0,0c2.2,0,4-1.8,4-4v-32h-8v28h-48v-48h28v-8h-32l0,0c-2.2,0-4,1.8-4,4v56C14.8,83.3,16.6,85.1,18.8,85.1z"></path> <polygon fill="currentColor" points="45.7,48.7 51.3,54.3 77.2,28.5 77.2,37.2 85.2,37.2 85.2,14.9 62.8,14.9 62.8,22.9 71.5,22.9"></polygon></svg> <span class="sr-only">(opens new window)</span></span></a></div> <!----></nav>  <ul class="sidebar-links"><li><section class="sidebar-group depth-0"><p class="sidebar-heading open"><span>利用Excutors异步执行任务</span> <!----></p> <ul class="sidebar-links sidebar-group-items"><li><a href="/docs/%E7%AC%94%E8%AE%B0/%E5%88%A9%E7%94%A8Excutors%E5%BC%82%E6%AD%A5%E6%89%A7%E8%A1%8C%E4%BB%BB%E5%8A%A1.html#excutors类" class="sidebar-link">Excutors类</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/docs/%E7%AC%94%E8%AE%B0/%E5%88%A9%E7%94%A8Excutors%E5%BC%82%E6%AD%A5%E6%89%A7%E8%A1%8C%E4%BB%BB%E5%8A%A1.html#executorservice" class="sidebar-link">ExecutorService</a><ul class="sidebar-sub-headers"></ul></li><li><a href="/docs/%E7%AC%94%E8%AE%B0/%E5%88%A9%E7%94%A8Excutors%E5%BC%82%E6%AD%A5%E6%89%A7%E8%A1%8C%E4%BB%BB%E5%8A%A1.html#future-对象" class="sidebar-link">Future 对象</a><ul class="sidebar-sub-headers"><li class="sidebar-sub-header"><a href="/docs/%E7%AC%94%E8%AE%B0/%E5%88%A9%E7%94%A8Excutors%E5%BC%82%E6%AD%A5%E6%89%A7%E8%A1%8C%E4%BB%BB%E5%8A%A1.html#future的主要方法" class="sidebar-link">Future的主要方法</a></li></ul></li></ul></section></li></ul> </aside> <main class="page"> <div class="theme-default-content content__default"><h1 id="利用excutors异步执行任务"><a href="#利用excutors异步执行任务" class="header-anchor">#</a> 利用Excutors异步执行任务</h1> <blockquote><p>起因是项目中，有一个接口是查询数据库，for循环查询了10次，特别|消耗时间，当时数据有100万条时，查询时间需要6,7秒 ,所以想异步查询数据库，然后得到自己想要的结果。</p></blockquote> <h2 id="excutors类"><a href="#excutors类" class="header-anchor">#</a> Excutors类</h2> <blockquote><p>Executors类，提供了一系列工厂方法用于创建线程池，返回的线程池都实现了ExecutorService接口。</p></blockquote> <p>可以利用Excutors 创建线程池</p> <ul><li>newCachedThreadPool创建一个可缓存线程池，如果线程池长度超过处理需要，可灵活回收空闲线程，若无可回收，则新建线程。</li> <li>newFixedThreadPool 创建一个定长线程池，可控制线程最大并发数，超出的线程会在队列中等待。</li> <li>newScheduledThreadPool 创建一个定长线程池，支持定时及周期性任务执行。</li> <li>newSingleThreadExecutor 创建一个单线程化的线程池，它只会用唯一的工作线程来执行任务，保证所有任务按照指定顺序(FIFO, LIFO, 优先级)执行。</li></ul> <div class="language-java extra-class"><pre class="language-java"><code> <span class="token class-name">ExecutorService</span> executorService <span class="token operator">=</span> <span class="token class-name">Executors</span><span class="token punctuation">.</span><span class="token function">newFixedThreadPool</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
</code></pre></div><p>创建线程池后，可以得到 ExecutorService 对象</p> <h2 id="executorservice"><a href="#executorservice" class="header-anchor">#</a> ExecutorService</h2> <blockquote><p>是一个比Executor使用更广泛的子类接口，其提供了生命周期管理的方法，返回 Future 对象，以及可跟踪一个或多个异步任务执行状况返回Future的方法；</p></blockquote> <p>可以调用ExecutorService的shutdown（）方法来平滑地关闭 ExecutorService，调用该方法后，将导致ExecutorService停止接受任何新的任务且等待已经提交的任务执行完成(已经提交的任务会分两类：</p> <ul><li><p>一类是已经在执行的，</p></li> <li><p>另一类是还没有开始执行的)，当所有已经提交的任务执行完毕后将会关闭ExecutorService。因此我们一般用该接口来实现和管理多线程。</p></li></ul> <p>通过 ExecutorService.submit() 方法返回的 <strong>Future</strong> 对象，可以调用**isDone（）**方法查询Future是否已经完成。</p> <p>当任务完成时，它具有一个结果，你可以调用**get()**方法来获取该结果。你也可以不用isDone（）进行检查就直接调用get()获取结果，在这种情况下，get()将阻塞，直至结果准备就绪，还可以取消任务的执行。</p> <p>Future 提供了 <strong>cancel()</strong> 方法用来取消执行 pending 中的任务。ExecutorService 部分代码如下：</p> <div class="language-java extra-class"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">interface</span> <span class="token class-name">ExecutorService</span> <span class="token keyword">extends</span> <span class="token class-name">Executor</span> <span class="token punctuation">{</span>
	<span class="token keyword">void</span> <span class="token function">shutdown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Future</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">submit</span><span class="token punctuation">(</span><span class="token class-name">Callable</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> task<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">Future</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token function">submit</span><span class="token punctuation">(</span><span class="token class-name">Runnable</span> task<span class="token punctuation">,</span> <span class="token class-name">T</span> result<span class="token punctuation">)</span><span class="token punctuation">;</span>
	<span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span></span> <span class="token class-name">List</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Future</span><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span><span class="token punctuation">&gt;</span></span> <span class="token function">invokeAll</span><span class="token punctuation">(</span><span class="token class-name">Collection</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token operator">?</span> <span class="token keyword">extends</span> <span class="token class-name">Callable</span><span class="token punctuation">&lt;</span><span class="token class-name">T</span><span class="token punctuation">&gt;</span><span class="token punctuation">&gt;</span></span> tasks<span class="token punctuation">,</span> <span class="token keyword">long</span> timeout<span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span> unit<span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">;</span>
<span class="token punctuation">}</span>
</code></pre></div><p>看到这，我们知道 ExecutorService 对象 可以接受 Callable 和 runnable 对象，返回Future 对象，说明我们可以定义自己的任务放在里面执行了！</p> <h2 id="future-对象"><a href="#future-对象" class="header-anchor">#</a> Future 对象</h2> <blockquote><p>Future表示一个可能还没有完成的异步任务的结果，针对这个结果可以添加Callback以便在任务执行成功或失败后作出相应的操作</p></blockquote> <h3 id="future的主要方法"><a href="#future的主要方法" class="header-anchor">#</a> Future的主要方法</h3> <div class="language-java extra-class"><pre class="language-java"><code>
    <span class="token comment">/**
     * 判断当前方法是否取消
     *
     * &lt;p&gt;After this method returns, subsequent calls to {@link #isDone} will
     * always return {@code true}.  Subsequent calls to {@link #isCancelled}
     * will always return {@code true} if this method returned {@code true}.
     *
     * @param mayInterruptIfRunning {@code true} if the thread executing this
     * task should be interrupted; otherwise, in-progress tasks are allowed
     * to complete
     * @return {@code false} if the task could not be cancelled,
     * typically because it has already completed normally;
     * {@code true} otherwise
     */</span>
    <span class="token keyword">boolean</span> <span class="token function">cancel</span><span class="token punctuation">(</span><span class="token keyword">boolean</span> mayInterruptIfRunning<span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * Returns {@code true} if this task was cancelled before it completed
     * normally.
     *
     * @return {@code true} if this task was cancelled before it completed
     */</span>
    <span class="token keyword">boolean</span> <span class="token function">isCancelled</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * Returns {@code true} if this task completed.
     *
     * Completion may be due to normal termination, an exception, or
     * cancellation -- in all of these cases, this method will return
     * {@code true}.
     *
     * @return {@code true} if this task completed
     */</span>
    <span class="token keyword">boolean</span> <span class="token function">isDone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * 在必要时等待计算完成，然后检索其结果。
     *
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     */</span>
    <span class="token class-name">V</span> <span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">,</span> <span class="token class-name">ExecutionException</span><span class="token punctuation">;</span>

    <span class="token comment">/**
     * 必要时最多等待给定时间以完成计算，然后检索其结果（如果有）
     *
     * @param timeout the maximum time to wait
     * @param unit the time unit of the timeout argument
     * @return the computed result
     * @throws CancellationException if the computation was cancelled
     * @throws ExecutionException if the computation threw an
     * exception
     * @throws InterruptedException if the current thread was interrupted
     * while waiting
     * @throws TimeoutException if the wait timed out
     */</span>
    <span class="token class-name">V</span> <span class="token function">get</span><span class="token punctuation">(</span><span class="token keyword">long</span> timeout<span class="token punctuation">,</span> <span class="token class-name">TimeUnit</span> unit<span class="token punctuation">)</span>
        <span class="token keyword">throws</span> <span class="token class-name">InterruptedException</span><span class="token punctuation">,</span> <span class="token class-name">ExecutionException</span><span class="token punctuation">,</span> <span class="token class-name">TimeoutException</span><span class="token punctuation">;</span>
</code></pre></div><ol><li><p>创建自己任务 ，我这里使用callable对象</p> <div class="language-java extra-class"><pre class="language-java"><code><span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">class</span>  <span class="token class-name">MyTask</span> <span class="token keyword">implements</span> <span class="token class-name">Callable</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> <span class="token punctuation">{</span>

        <span class="token annotation punctuation">@Override</span>
        <span class="token keyword">public</span> <span class="token class-name">Integer</span> <span class="token function">call</span><span class="token punctuation">(</span><span class="token punctuation">)</span> <span class="token keyword">throws</span> <span class="token class-name">Exception</span> <span class="token punctuation">{</span>
            
            <span class="token keyword">long</span> start <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token comment">// 睡眠 5秒</span>
            <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">sleep</span><span class="token punctuation">(</span><span class="token number">5000</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">String</span> name <span class="token operator">=</span> <span class="token class-name">Thread</span><span class="token punctuation">.</span><span class="token function">currentThread</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">.</span><span class="token function">getName</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;方法执行任务成功    thread name: &quot;</span> <span class="token operator">+</span> name<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">long</span> end <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;花费时间 = &quot;</span> <span class="token operator">+</span> <span class="token punctuation">(</span>end <span class="token operator">-</span> start<span class="token punctuation">)</span><span class="token operator">/</span><span class="token number">1000.0</span><span class="token operator">+</span><span class="token string">&quot;秒&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token keyword">return</span> <span class="token number">1</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>
    <span class="token punctuation">}</span>
</code></pre></div></li> <li><p>demo代码</p></li></ol> <div class="language-java extra-class"><pre class="language-java"><code> <span class="token keyword">public</span> <span class="token keyword">static</span> <span class="token keyword">void</span> <span class="token function">main</span><span class="token punctuation">(</span><span class="token class-name">String</span><span class="token punctuation">[</span><span class="token punctuation">]</span> args<span class="token punctuation">)</span>  <span class="token punctuation">{</span>

        <span class="token comment">// 创建线程池</span>
        <span class="token class-name">ExecutorService</span> executorService <span class="token operator">=</span> <span class="token class-name">Executors</span><span class="token punctuation">.</span><span class="token function">newFixedThreadPool</span><span class="token punctuation">(</span><span class="token number">10</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 创建list 装 Future 对象</span>
        <span class="token class-name">LinkedList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Future</span><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span><span class="token punctuation">&gt;</span></span> futures <span class="token operator">=</span> <span class="token keyword">new</span> <span class="token class-name">LinkedList</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token punctuation">&gt;</span></span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token comment">// 开始时间</span>
        <span class="token keyword">long</span> start <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> startStr <span class="token operator">=</span> <span class="token class-name">DateUtils</span><span class="token punctuation">.</span><span class="token function">parseString</span><span class="token punctuation">(</span>start<span class="token punctuation">,</span> <span class="token class-name">DateUtils</span><span class="token punctuation">.</span>DEFAULT_FORMAT<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;开始执行..开始时间： = &quot;</span> <span class="token operator">+</span> startStr<span class="token punctuation">)</span><span class="token punctuation">;</span>

        <span class="token comment">// 循环执行10次</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token keyword">int</span> i <span class="token operator">=</span> <span class="token number">0</span><span class="token punctuation">;</span> i <span class="token operator">&lt;</span> <span class="token number">10</span><span class="token punctuation">;</span> i<span class="token operator">++</span><span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment">// 执行任务</span>
            <span class="token class-name">Future</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> future <span class="token operator">=</span> executorService<span class="token punctuation">.</span><span class="token function">submit</span><span class="token punctuation">(</span><span class="token keyword">new</span> <span class="token class-name">MyTask</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token comment">// add</span>
            futures<span class="token punctuation">.</span><span class="token function">add</span><span class="token punctuation">(</span>future<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token punctuation">}</span>

        <span class="token comment">// 判断每个任务是否完成 ，如果未完成则阻塞，完成放行</span>
        <span class="token keyword">for</span> <span class="token punctuation">(</span><span class="token class-name">Future</span><span class="token generics"><span class="token punctuation">&lt;</span><span class="token class-name">Integer</span><span class="token punctuation">&gt;</span></span> future <span class="token operator">:</span> futures<span class="token punctuation">)</span> <span class="token punctuation">{</span>
            <span class="token comment">// 死循环 判断该线程任务是否执行完</span>
            <span class="token keyword">while</span> <span class="token punctuation">(</span><span class="token operator">!</span>future<span class="token punctuation">.</span><span class="token function">isDone</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">)</span><span class="token punctuation">{</span><span class="token punctuation">}</span>
            <span class="token comment">// 返回执行结果</span>
            <span class="token class-name">Integer</span> result <span class="token operator">=</span> <span class="token keyword">null</span><span class="token punctuation">;</span>
            <span class="token keyword">try</span> <span class="token punctuation">{</span>
                <span class="token comment">// 获取执行结果</span>
                result <span class="token operator">=</span> future<span class="token punctuation">.</span><span class="token function">get</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
                <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;result = &quot;</span> <span class="token operator">+</span> result<span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">InterruptedException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">catch</span> <span class="token punctuation">(</span><span class="token class-name">ExecutionException</span> e<span class="token punctuation">)</span> <span class="token punctuation">{</span>
                e<span class="token punctuation">.</span><span class="token function">printStackTrace</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span> <span class="token keyword">finally</span> <span class="token punctuation">{</span>
                <span class="token comment">// 启动有序关闭，在该关闭中执行先前提交的任务，但不接受任何新任务。 如果调用已经关闭，则调用不会产生任何其他影响。</span>
                executorService<span class="token punctuation">.</span><span class="token function">shutdown</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
            <span class="token punctuation">}</span>


        <span class="token punctuation">}</span>

        <span class="token comment">// 打印结束时间</span>
        <span class="token keyword">long</span> end <span class="token operator">=</span> <span class="token class-name">System</span><span class="token punctuation">.</span><span class="token function">currentTimeMillis</span><span class="token punctuation">(</span><span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">String</span> endStr <span class="token operator">=</span> <span class="token class-name">DateUtils</span><span class="token punctuation">.</span><span class="token function">parseString</span><span class="token punctuation">(</span>end<span class="token punctuation">,</span> <span class="token class-name">DateUtils</span><span class="token punctuation">.</span>DEFAULT_FORMAT<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;结束时间 = &quot;</span> <span class="token operator">+</span> endStr<span class="token punctuation">)</span><span class="token punctuation">;</span>
        <span class="token class-name">Long</span> dif <span class="token operator">=</span> end <span class="token operator">-</span> start<span class="token punctuation">;</span>
        <span class="token comment">// 打印消耗时间</span>
        <span class="token class-name">System</span><span class="token punctuation">.</span>out<span class="token punctuation">.</span><span class="token function">println</span><span class="token punctuation">(</span><span class="token string">&quot;总共花费时间 = &quot;</span> <span class="token operator">+</span> dif<span class="token operator">/</span><span class="token number">1000.0</span><span class="token operator">+</span><span class="token string">&quot;秒&quot;</span><span class="token punctuation">)</span><span class="token punctuation">;</span>


    <span class="token punctuation">}</span>
</code></pre></div><ol start="3"><li>执行结果</li></ol> <div class="language-shell extra-class"><pre class="language-shell"><code>
开始执行<span class="token punctuation">..</span>开始时间： <span class="token operator">=</span> <span class="token number">2020</span>-12-08 00:42:08
方法执行任务成功    thread name: pool-1-thread-7
方法执行任务成功    thread name: pool-1-thread-10
方法执行任务成功    thread name: pool-1-thread-9
方法执行任务成功    thread name: pool-1-thread-8
方法执行任务成功    thread name: pool-1-thread-6
方法执行任务成功    thread name: pool-1-thread-4
方法执行任务成功    thread name: pool-1-thread-2
方法执行任务成功    thread name: pool-1-thread-1
方法执行任务成功    thread name: pool-1-thread-5
方法执行任务成功    thread name: pool-1-thread-3
花费时间 <span class="token operator">=</span> <span class="token number">5.001</span>秒
花费时间 <span class="token operator">=</span> <span class="token number">5.001</span>秒
花费时间 <span class="token operator">=</span> <span class="token number">5.001</span>秒
花费时间 <span class="token operator">=</span> <span class="token number">5.001</span>秒
花费时间 <span class="token operator">=</span> <span class="token number">5.001</span>秒
花费时间 <span class="token operator">=</span> <span class="token number">5.001</span>秒
花费时间 <span class="token operator">=</span> <span class="token number">5.001</span>秒
result <span class="token operator">=</span> <span class="token number">1</span>
花费时间 <span class="token operator">=</span> <span class="token number">5.001</span>秒
花费时间 <span class="token operator">=</span> <span class="token number">5.002</span>秒
花费时间 <span class="token operator">=</span> <span class="token number">5.002</span>秒
result <span class="token operator">=</span> <span class="token number">1</span>
result <span class="token operator">=</span> <span class="token number">1</span>
result <span class="token operator">=</span> <span class="token number">1</span>
result <span class="token operator">=</span> <span class="token number">1</span>
result <span class="token operator">=</span> <span class="token number">1</span>
result <span class="token operator">=</span> <span class="token number">1</span>
result <span class="token operator">=</span> <span class="token number">1</span>
result <span class="token operator">=</span> <span class="token number">1</span>
result <span class="token operator">=</span> <span class="token number">1</span>
结束时间 <span class="token operator">=</span> <span class="token number">2020</span>-12-08 00:42:13
总共花费时间 <span class="token operator">=</span> <span class="token number">5.073</span>秒
Disconnected from the target VM, address: <span class="token string">'127.0.0.1:0'</span>, transport: <span class="token string">'socket'</span>

Process finished with <span class="token builtin class-name">exit</span> code <span class="token number">0</span>
</code></pre></div></div> <footer class="page-edit"><!----> <!----></footer> <!----> </main></div><div class="global-ui"></div></div>
    <script src="/docs/assets/js/app.491c5ace.js" defer></script><script src="/docs/assets/js/2.dc29a537.js" defer></script><script src="/docs/assets/js/13.c24cbb66.js" defer></script>
  </body>
</html>
